import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'home.dart';
import 'joke.dart';
import 'random_joke_provider.dart';

void main() {
  runApp(const ProviderApp());
}

class ProviderApp extends StatefulWidget {
  const ProviderApp({super.key});

  @override
  State<ProviderApp> createState() => _ProviderAppState();
}

class _ProviderAppState extends State<ProviderApp> {
  int _refreshId = 0;
  RandomJokeState _latestState = const RandomJokeState.loading();

  void _refresh() {
    setState(() {
      _refreshId++;
      _latestState =
          _latestState.hasJoke
              ? RandomJokeState.loadingWithPrevious(_latestState.joke)
              : const RandomJokeState.loading();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<RefreshJokeCallback>.value(value: _refresh),
        FutureProvider<RandomJokeState>(
          key: ValueKey(_refreshId),
          initialData: _latestState,
          catchError: (_, error) {
            final resolvedError =
                error ?? Exception('Unknown error while fetching a joke');
            final state = RandomJokeState.error(
              resolvedError,
              previous: _latestState.joke,
            );
            if (mounted) {
              _latestState = state;
            }
            return state;
          },
          create: (_) async {
            final joke = await fetchRandomJoke();
            final state = RandomJokeState.success(joke);
            if (mounted) {
              _latestState = state;
            }
            return state;
          },
        ),
      ],
      child: const MyApp(),
    );
  }
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: HomeView());
  }
}
